package com.sicong.common.security.utils;

import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class TokenUtil {

    /**
     * 过期时间 24 小时
     */
    private static long EXPIRE_TIME = 60 * 24 * 60 * 1000;

    @Value("${jwt.expire:86400000}")
    private void setExpireTime(Long expireTime) {
        EXPIRE_TIME = expireTime;
    }

    /**
     * 密钥
     */
    private static String SECRET;
    @Value("${jwt.secret:oKWI6r6tRbE0MGSF3DbXkWDVBnBMyIQL}")
    private void setSecret(String secret) {
        SECRET = secret;
    }

    /**
     * 通过用户名生成token
     */
    public String createToken(String username) {
        return Jwts.builder().setSubject(username)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .signWith(SignatureAlgorithm.HS512,SECRET)
                .compressWith(CompressionCodecs.GZIP)
                .compact();
    }

    /**
     * 根据token字符串得到用户名
     */
    public String getUsernameFromToken(String token) {
        Claims body = Jwts.parser().setSigningKey(SECRET)
                .parseClaimsJws(token).getBody();
        System.out.println(body.toString());
        return body.getSubject();
    }

}
